package com.newlink.building.main.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.newlink.building.common_base.constant.*
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.DeviceData
import com.newlink.building.common_base.model.bean.DoorData
import com.newlink.building.common_base.utils.MqttDoorOperator
import com.newlink.building.common_base.utils.NetWorkUtil
import com.newlink.building.common_base.utils.TimezoneConvert
import com.newlink.building.common_base.utils.logDebug
import com.newlink.building.common_base.widget.SpaceItemDecoration
import com.newlink.building.main.R
import com.newlink.building.manager.Module_Phone_VoipController

/**
 * Created by xiaodong on 2022/8/30.
 */
class Module_Main_HomeAdapter :
    BaseQuickAdapter<DeviceData, BaseViewHolder>(R.layout.item_door_access), LoadMoreModule,
    OnItemChildClickListener {

    private var openDoorClickListener: OpenDoorClickListener? = null

    init {
        addChildClickViewIds(
            R.id.ll_monitor,
            R.id.ll_makecall,
            R.id.ll_opendoor,
            R.id.ll_record,
            R.id.ll_security
        )
        setOnItemChildClickListener(this)
    }

    override fun convert(holder: BaseViewHolder, item: DeviceData) {

        //devType 1室内机 2门禁 3话机 4APP 5管理机
        when (item.devType) {
            //话机需要根据有无摄像头来显示监控
            Base_DeviceType.INDOOR.code, Base_DeviceType.IPPHONE.code, Base_DeviceType.IntercomManager.code -> {
                holder.setGone(R.id.ll_monitor, true)
                holder.setGone(R.id.ll_opendoor, true)
            }

            Base_DeviceType.DOORPHONE.code -> {
                holder.setGone(R.id.ll_monitor, false)
                holder.setGone(R.id.ll_opendoor, item.doors?.size ?: 0 == 0)
            }

            else -> {
                holder.setGone(R.id.ll_monitor, true)
                holder.setGone(R.id.ll_opendoor, true)
            }
        }
        holder.setGone(R.id.ll_security, item.enableArming == 0)
        holder.setText(R.id.tv_device_name, item.devName)
//        holder.setGone(R.id.ll_record, item.isPublic == 1)
        holder.setGone(R.id.ll_record, true)//暂时隐藏查看单独设备记录功能,后续看需求
        //TODO 0未配置1离线2在线
        if (item.devStatus == Base_DeviceStatus.ONLINE.status && item.cMqttConnected) {
//        if (item.devStatus == 0) {
            holder.setGone(R.id.tv_device_state, true)
            holder.setBackgroundResource(
                R.id.tv_device_circle,
                R.drawable.device_state_online
            )
            holder.setTextColor(
                R.id.tv_device_name,
                ContextCompat.getColor(context, R.color.textColorPrimary)
            )
            holder.getView<TextView>(R.id.tv_device_name).layoutParams
            holder.setTextColor(
                R.id.tv_device_state,
                ContextCompat.getColor(context, R.color.color_00ad0c)
            )
            holder.getView<ImageView>(R.id.image_monitor)
                .setColorFilter(ContextCompat.getColor(context, R.color.transparent))
            holder.getView<ImageView>(R.id.image_makecall)
                .setColorFilter(ContextCompat.getColor(context, R.color.transparent))
            holder.getView<ImageView>(R.id.image_opendoor)
                .setColorFilter(ContextCompat.getColor(context, R.color.transparent))
            holder.getView<ImageView>(R.id.image_record)
                .setColorFilter(ContextCompat.getColor(context, R.color.transparent))
            holder.getView<ImageView>(R.id.image_security)
                .setColorFilter(ContextCompat.getColor(context, R.color.transparent))

            holder.setVisible(R.id.iv_bluetooth_support, item.bluetooth)

            holder.getView<ImageView>(R.id.iv_bluetooth_support).setOnClickListener {
                openDoorClickListener?.onBtIconClicked()
            }

        } else {
            holder.setGone(R.id.tv_device_state, item.lastTimeUnix == 0L)
            if (!item.cMqttConnected && item.devStatus == Base_DeviceStatus.ONLINE.status) {
                holder.setGone(R.id.tv_device_state, true)
            }
            holder.setText(
                R.id.tv_device_state,
//                context.getString(R.string.time_device_offline , TimezoneConvert.convertTimeFromGMTToLocal(item.lastTime.orEmpty()))
                context.getString(
                    R.string.time_device_offline,
                    TimezoneConvert.formatTimestamp(item.lastTimeUnix)
                )
            )
            holder.getView<ImageView>(R.id.image_monitor)
                .setColorFilter(ContextCompat.getColor(context, R.color.color_ccf0f0f0))
            holder.getView<ImageView>(R.id.image_makecall)
                .setColorFilter(ContextCompat.getColor(context, R.color.color_ccf0f0f0))
            holder.getView<ImageView>(R.id.image_opendoor)
                .setColorFilter(ContextCompat.getColor(context, R.color.color_ccf0f0f0))
            holder.getView<ImageView>(R.id.image_record)
                .setColorFilter(ContextCompat.getColor(context, R.color.color_ccf0f0f0))
            holder.getView<ImageView>(R.id.image_security)
                .setColorFilter(ContextCompat.getColor(context, R.color.color_ccf0f0f0))

            holder.setBackgroundResource(R.id.tv_device_circle, R.drawable.device_state_offline)
            holder.setTextColor(
                R.id.tv_device_name,
                ContextCompat.getColor(context, R.color.color_bfbfbf)
            )
            holder.setTextColor(
                R.id.tv_device_state,
                ContextCompat.getColor(context, R.color.color_bfbfbf)
            )
            holder.setVisible(R.id.iv_bluetooth_support, false)
        }
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = adapter.getItem(position) as DeviceData
        when (view.id) {
            R.id.ll_monitor -> {
                if (!checkDevStatus(item)) {
                    return
                }
//                RinoCallManager.get().makeInvite(item.sip.orEmpty(), true)
//                VoipController.get().makeMonitorCall(item.mac.orEmpty())
                if (Module_Phone_VoipController.get().isCallingState()) {
                    showToast(context.getString(R.string.outgoing_call_not_invite_again))
                    return
                }
                openDoorClickListener?.makeMonitorCall(
                    item.devType,
                    item.aid.toString(),
                    item.devName.orEmpty()
                )

            }

            R.id.ll_makecall -> {
                if (!checkDevStatus(item)) {
                    return
                }
                if (Module_Phone_VoipController.get().isCallingState()) {
                    showToast(context.getString(R.string.outgoing_call_not_invite_again))
                    return
                }
                openDoorClickListener?.makeCall(
                    item.devType,
                    item.aid.toString(),
                    item.devName.orEmpty()
                )
            }

            R.id.ll_opendoor -> {
                if (!checkDevStatus(item)) {
                    return
                }
                openDoorClickListener?.openDoorClick(view, position)
            }

            R.id.ll_record -> {
                if (!checkDevStatus(item)) {
                    return
                }
                ARouter.getInstance().build(Base_RouterPath.PATH_HOME)
                    .withInt(NL_Key.TAB_INDEX, 2).navigation()
            }

            R.id.ll_security -> {
//                if (!checkDevStatus(item)) {
//                    return
//                }
                openDoorClickListener?.securityClick(view, position)
            }
        }
    }

    private fun checkDevStatus(item: DeviceData): Boolean {
        if (!NetWorkUtil.isNetworkAvailable(context)) {
            showToast(context.getString(R.string.call_error_network_unreachable))
            return false
        }
        if (item.devStatus !== Base_DeviceStatus.ONLINE.status) {
//            showToast(context.getString(R.string.device_is_offline))
            return false
        }
        return true
    }

    fun showBottomSheetDialog(position: Int, data: MutableList<DoorData>) {
        val bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
        bottomSheetDialog.setCanceledOnTouchOutside(true)
//            bottomSheetDialog?.window?.setDimAmount(0f);
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_lock_select, null, false)
        val recyclerView = view.findViewById(R.id.locksRecyclerView) as RecyclerView
        view.findViewById<ImageView>(R.id.image_cancel).setOnClickListener {
            bottomSheetDialog.dismiss()
        }

        val lockListAdapter = Module_Main_LockListAdapter(data)
        recyclerView.adapter = lockListAdapter
        recyclerView.addItemDecoration(SpaceItemDecoration(context))

        lockListAdapter.setOnItemChildClickListener { _, _, index ->
//            openDoor(context, data[position].mac ,position)
            openDoorClickListener?.doorLockClick(view, position, data[index].doorNo)
            bottomSheetDialog.dismiss()
        }

        bottomSheetDialog.setContentView(view)
        bottomSheetDialog.show()
    }

    private fun openDoor(context: Context, mac: String, position: Int) {
        val sp = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
        val userId = sp.getLong(Base_Constant.USER_ID_KEY, 0L)
        logDebug<Module_Main_HomeAdapter>("open door mac is $mac  userid $userId")
//        DoorOperator.sendOpenDoorAction(userId, mac, position+1, DoorOperator.ACTION_OPEN_DOOR)
        MqttDoorOperator.sendOpenDoorAction(
            userId,
            mac,
            position + 1,
            MqttDoorOperator.ACTION_OPEN_DOOR
        )

    }

    interface OpenDoorClickListener {
        fun openDoorClick(view: View, position: Int)

        //index为门锁下标,对应doorNo
        fun doorLockClick(view: View, position: Int, index: Int)
        fun securityClick(view: View, position: Int)

        fun makeCall(type: Int, sip: String, devName: String)
        fun makeMonitorCall(type: Int, sip: String, devName: String)
        fun onBtIconClicked()
    }

    fun setOnOpenDoorClickListener(listner: OpenDoorClickListener) {
        this.openDoorClickListener = listner
    }
}